package com.enbatis.mybatisplugs.controller;

import com.enbatis.mybatisplugs.base.Account;
import com.enbatis.mybatisplugs.base.BaseController;
import com.enbatis.mybatisplugs.commons.sql.Wrapper;
import com.enbatis.mybatisplugs.commons.utils.CodeMsg;
import com.enbatis.mybatisplugs.commons.utils.MD5Util;
import com.enbatis.mybatisplugs.commons.utils.ResultReturn;

import com.enbatis.mybatisplugs.entity.LoginLog;
import com.enbatis.mybatisplugs.entity.SysUser;
import com.enbatis.mybatisplugs.service.LoginLogService;
import com.enbatis.mybatisplugs.service.SysUserService;
import com.enbatis.mybatisplugs.toolkit.AddressUtils;
import com.enbatis.mybatisplugs.toolkit.CusAccessObjectUtil;
import com.enbatis.mybatisplugs.toolkit.LoginCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;


@RestController
@RequestMapping("v1/login")
@Slf4j
public class LoginController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private LoginLogService loginLogService;

    @Value("${service.domain}")
    private String domain;

    @RequestMapping("/test")
    public String test(Model model){

        model.addAttribute("name","王卫东是");

        return "test";
    }


    @PostMapping("/login")
    public ResultReturn login(SysUser user){


       Cookie[] cookies=request.getCookies();
       if (null!=cookies){
           for (Cookie c:cookies) {
               if (LoginCacheUtil.loginUser.get(c.getValue())!=null){
                   return  success("/");
               }
           }

       }
       String username =request.getParameter("username");
       String password= MD5Util.generate(request.getParameter("password"));

        List<SysUser> list= sysUserService.list(new Wrapper<>(user).eq("username",username).eq("password",password));
        Optional<SysUser> first= list.stream().filter(dbUser->dbUser.getUsername().equals(user.getUsername())&&dbUser.getPassword().equals(password)).findFirst();

        if (first.isPresent()){
            user.setUsername(username);
            String token= UUID.randomUUID().toString();
            HttpSession session=request.getSession();
            session.setAttribute("TOKEN",user);
            Cookie cookie=new Cookie("TOKEN",token);
            cookie.setDomain(domain);
            cookie.setPath("/");
            response.addCookie(cookie);
            Account account=new Account();
            account.setId(first.get().getId());
            account.setUsername(first.get().getUsername());
            account.setCompanyId(first.get().getCompanyId());
            LoginCacheUtil.loginUser.put(token,account);

            try {
                String ip=  CusAccessObjectUtil.getIpAddress(request);
                   String address=  AddressUtils.getAddresses(ip);
                LoginLog log=new LoginLog();
                  log.setAddress(address);
                log.setIp(ip);
                log.setUserId(account.getId());
                log.setUsername(account.getUsername());
                log.setCtime(new Date());
                loginLogService.insert(log);
            }catch (Exception e){
               log.error("登录失败"+e.getMessage(),e);
            }

            return  success("/");

        }else{
            return failed(CodeMsg.LOGIN_USER_PSD_ERROR);
        }

    }


    @RequestMapping("/add")
    public String add(){
        return "/user/add";
    }


    @RequestMapping("/update")
    public String update(){
        return "/user/update";
    }


    @RequestMapping("/tologin")
    public String toLogin(){
        return "login";
    }


    @RequestMapping("/unAuth")
    public String unAuth(){
        return "unAuth";
    }



    @GetMapping("/user_info")
    public ResultReturn<Account> test(){
        return success(getAccount());
    }

    @PostMapping("/login_out")
    public ResultReturn loginOut(){
         Cookie [] cookies=request.getCookies();
         if (null!=cookies&&cookies.length>0){
             for (Cookie cookie:cookies) {
                 String value=cookie.getValue();
                 if ( LoginCacheUtil.loginUser.containsKey(value)){
                     LoginCacheUtil.loginUser.remove(value);
                   return success(true) ;
                 }

             }
         }
         return failed(CodeMsg.SERVER_EXCEPTION);
    }


//    @Autowired
//    private HelloSender helloSender;
//    @GetMapping("/rabbit_mq_hello")
//    public String hello() throws Exception {
//        helloSender.send();
//        return "";
//    }



}
